package com.yzt.zhuju.widget;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.PopupWindow;

/**
 * author : bob
 * date   : 2022/12/2
 * desc   :
 */
public class BasePopupWindow implements View.OnTouchListener, PopupWindow.OnDismissListener {
    protected PopupWindow popupWindow;
    protected Activity mContext;
    protected View mView;
    protected LayoutInflater inflater;
    protected AdapterView.OnItemClickListener onItemClickListener;
    protected View.OnClickListener clickListener;
    protected Window window;

    private PopupWindow.OnDismissListener onDismissListener;

    public BasePopupWindow(Activity mContext) {
        this.mContext = mContext;
        popupWindow = new PopupWindow(mContext);
        inflater = LayoutInflater.from(mContext);
        window = mContext.getWindow();
    }

    protected void initPopupWindow() {
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(this);
        popupWindow.setFocusable(true);
        popupWindow.setOnDismissListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
            dismiss();
            return true;
        }
        return false;
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setClickListener(View.OnClickListener clickListener) {
        this.clickListener = clickListener;
    }

    @Override
    public void onDismiss() {
        if (onDismissListener != null) {
            onDismissListener.onDismiss();
        }
    }

    public void showAtLocation(View parent, int gravity, int x, int y) {
        popupWindow.showAtLocation(parent, gravity, x, y);
    }

    public void show() {
        popupWindow.dismiss();
    }

    public void showAsDropDown(View anchor, int xoff, int yoff) {
        if (popupWindow != null) {
            popupWindow.showAsDropDown(anchor, xoff, yoff);
        }
    }

    public void dismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }

        WindowManager.LayoutParams params = window.getAttributes();
        params.alpha = 1f;
        window.setAttributes(params);
    }

    public boolean isShowing() {
        if (popupWindow != null) {
            return popupWindow.isShowing();
        }
        return false;
    }

    public void setOnDismissListener(PopupWindow.OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

}
